/**
 * 
 */
package com.gs.librarian.web.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import org.apache.log4j.Logger;

import com.gs.librarian.web.config.CaptchaConfiguration;

/**
 * @author sabuj.das
 *
 */
public class ApplicationSessionListener {

	private static final Logger logger = Logger.getLogger(ApplicationSessionListener.class);
	
	public void sessionCreated(HttpSessionEvent sessionEvent) {
		HttpSession session = sessionEvent.getSession();
		logger.info("Session created with ID: " + session.getId());
    	ServletContext context = session.getServletContext();
    	String config = context.getInitParameter(CaptchaConfiguration.RECAPTCHA_CONFIG_LOCATION);
    	
    	if (config == null) {
			throw new RuntimeException(String.format("failure to specify context init-param - %s", CaptchaConfiguration.RECAPTCHA_CONFIG_LOCATION));
		}
    	
    	InputStream is = null;

		try {
			is = getResourceStream(config, context);
			CaptchaConfiguration captchaConfiguration = CaptchaConfiguration.configure(is);
			if(null != captchaConfiguration){
				session.setAttribute(CaptchaConfiguration.RECAPTCHA_CONFIGURATION, captchaConfiguration);
			} else {
				throw new RuntimeException("failure to create CAPTCHA configuration");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if(null != is){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private InputStream getResourceStream(String resourceName, ServletContext context) throws IOException {
		InputStream is = null;

		/** try classpath **/
		is = getClass().getClassLoader().getResourceAsStream(resourceName);

		/** try web context **/
		if (is == null) {
			String fileName = context.getRealPath(resourceName);
			File file = new File(fileName);

			if (file.exists()) {
				is = new FileInputStream(fileName);
			}
		}

		/** try current directory **/
		if (is == null) {
			File file = new File(resourceName);

			if (file.exists()) {
				is = new FileInputStream(resourceName);
			}
		}

		/** fail if still empty **/
		if (is == null) {
			throw new IOException(String.format("unable to locate resource - %s", resourceName));
		}

		return is;
	}
	
	
	public void sessionDestroyed(HttpSessionEvent sessionEvent) {
		if(null != sessionEvent.getSession()){
			sessionEvent.getSession().setAttribute(CaptchaConfiguration.RECAPTCHA_CONFIGURATION, null);
			logger.info("Session destroyed with ID: " + sessionEvent.getSession().getId());
		}
	}
	
}
